#include<iostream>
#include<vector>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
using namespace std;
typedef void (*handerl_t)();


vector<handerl_t> handlers;

void f1()
{
   cout<<"方法一"<<endl; 
}

void f2()
{
    cout<<"方法二"<<endl;
}

void Lode()
{
    handlers.push_back(f1);
    handlers.push_back(f2);
}

int main()
{
    pid_t id = fork();

    if(id < 0)
    {
        cout<<"创建子进程错误"<<endl;
        return 1;
    }
    else if( id == 0 )
    {
        int cnt = 5;
        while(cnt--)
        {
            cout<<"子进程：pid:"<<getpid()<<"父进程："<<getppid()<<endl;
            sleep(1);
        }

    }
    else 
    {
        int status = 0;
        int quit = 0;
        while(!quit)
        {
             pid_t ret = waitpid(-1,&status,WNOHANG); 

             if(ret >0)
             {
                 cout<<"等待成功，退出信号："<< WIFEXITED(status)<<"退出码："<<WEXITSTATUS(status)<<endl;
                 quit = 1;  
             }
             else if( ret <0 )
             {
                 cout<<"退出错误"<<endl;
                 quit =1;
             }
             else 
             {
                cout<<"程序正在进行"<<endl;
                if(handlers.empty())
                {
                    Lode();
                }
                for(auto e : handlers)
                {
                    e();
                }
                sleep(1);
             }
        }
    }
    return 0;
}
